package com.genreate.domain.page;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.exceptions.UtilException;
import cn.hutool.core.lang.Opt;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分页查询实体类
 *
 * @author Lion Li
 */

@Data
public class PageQuery implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 分页大小
     */
    private Integer pageSize;

    /**
     * 当前页数
     */
    private Integer pageNum;

    /**
     * 排序列
     */
    private String orderByColumn;

    /**
     * 排序的方向desc或者asc
     */
    private String isAsc;

    /**
     * 当前记录起始索引 默认值
     */
    public static final int DEFAULT_PAGE_NUM = 1;

    /**
     * 每页显示记录数 默认值 默认查全部
     */
    public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE;

    public <T> Page<T> build() {
        Integer pageNum = ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM);
        Integer pageSize = ObjectUtil.defaultIfNull(getPageSize(), DEFAULT_PAGE_SIZE);
        if (pageNum <= 0) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        Page<T> page = new Page<>(pageNum, pageSize);
        List<OrderItem> orderItems = buildOrderItem();
        if (CollUtil.isNotEmpty(orderItems)) {
            page.addOrder(orderItems.toArray(new OrderItem[0]));
        }
        return page;
    }

    /**
     * 构建排序
     * <p>
     * 支持的用法如下:
     * {isAsc:"asc",orderByColumn:"id"} order by id asc
     * {isAsc:"asc",orderByColumn:"id,createTime"} order by id asc,create_time asc
     * {isAsc:"desc",orderByColumn:"id,createTime"} order by id desc,create_time desc
     * {isAsc:"asc,desc",orderByColumn:"id,createTime"} order by id asc,create_time desc
     */
    public List<OrderItem> buildOrderItem() {
        if (StrUtil.isBlank(orderByColumn) || StrUtil.isBlank(isAsc)) {
            return null;
        }
        String orderBy = escapeOrderBySql(orderByColumn);
        orderBy = StrUtil.toUnderlineCase(orderBy);

        // 兼容前端排序类型
        isAsc = StrUtil.replace(isAsc, "ascending" , "asc");
        isAsc = StrUtil.replace(isAsc, "descending" , "desc");

        String[] orderByArr = orderBy.split(",");
        String[] isAscArr = isAsc.split(",");
        if (isAscArr.length != 1 && isAscArr.length != orderByArr.length) {
            throw new RuntimeException("排序参数有误");
        }

        List<OrderItem> list = new ArrayList<>();
        // 每个字段各自排序
        for (int i = 0; i < orderByArr.length; i++) {
            String orderByStr = orderByArr[i];
            String isAscStr = isAscArr.length == 1 ? isAscArr[0] : isAscArr[i];
            if ("asc".equals(isAscStr)) {
                list.add(OrderItem.asc(orderByStr));
            } else if ("desc".equals(isAscStr)) {
                list.add(OrderItem.desc(orderByStr));
            } else {
                throw new RuntimeException("排序参数有误");
            }
        }
        return list;
    }


    /**
     * 检查字符，防止注入绕过
     */
    public static String escapeOrderBySql(String value) {
        if (StrUtil.isNotEmpty(value) && !isValidOrderBySql(value)) {
            throw new UtilException("参数不符合规范，不能进行查询");
        }
        return value;
    }

    /**
     * 验证 order by 语法是否符合规范
     */
    public static boolean isValidOrderBySql(String value) {
        /**
         * 仅支持字母、数字、下划线、空格、逗号、小数点（支持多个字段排序）
         */
        final String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+";
        return value.matches(SQL_PATTERN);
    }

    /**
     * 自定义 stream 分页
     *
     * @param dataList 数据列表
     * @param pageNum  页码
     * @param pageSize 页面大小
     * @return {@link TableDataInfo }<{@link T }>
     */
    public static <T> TableDataInfo<T> customPage(List<T> dataList, Integer pageNum, Integer pageSize) {
        TableDataInfo rspData = new TableDataInfo();
        if (IterUtil.isEmpty(dataList)) {
            return rspData;
        }
        //默认页数
        int defaultPageNum = 1;
        //默认条数
        int defaultPageSize = 10;

        if (pageNum == null || pageNum < 1) {
            pageNum = defaultPageNum;
        }
        Opt.ofNullable(pageNum).map(e -> e < defaultPageNum ? defaultPageNum : e).orElseGet(() -> defaultPageNum);
        Opt.ofNullable(pageSize).orElse(defaultPageSize);

        //获取 从哪一条开始查询
        int skip = (pageNum - 1) * defaultPageSize;

        rspData.setTotal(dataList.size());
        List<T> collect = dataList.stream()
                .skip(skip).limit(pageSize)
                .collect(Collectors.toList());
        rspData.setRows(collect);
        return rspData;
    }
}
